from django.shortcuts import render, get_object_or_404
from .models import Article
from markdown import markdown

def post_list(request):
    posts = Article.objects.all()
    return render(request, 'blog/post_list.html', {'posts': posts})

def post_detail(request, pk):
    post = get_object_or_404(Article, pk=pk)
    return render(request, 'blog/post_detail.html', {'post': post})


folder_path="../ChaselWang.github.io/source/_posts"

import os
from .models import Article



from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from .models import Article
from os import listdir
from os.path import isfile, join

@csrf_exempt
def import_md_to_database(request):
    # 假设你有一个从 URL 参数中提取的文件夹路径
    directory = request.GET.get('directory', '../ChaselWang.github.io/source/_posts')

    # 构建完整的文件路径
    file_path = os.path.join(directory, '')  # 确保以斜杠结束，以避免路径拼接错误

    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith('.md'):
                file_path = os.path.join(root, file)
                category = os.path.basename(root)
                title = os.path.splitext(file)[0]
                # created_at = datetime.datetime.fromtimestamp(os.path.getctime(file_path))
                # updated_at = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
                
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                    article, created = Article.objects.get_or_create(title=file.split('.')[0])
                    article.content = content
                    article.html_content = markdown(content)
                # 保存到数据库
                    article.save()
        return HttpResponse('Markdown 文章已成功导入数据库。')
